package com.xinyu.utils;
import io.jsonwebtoken.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    private static final String SECRET_KEY = "mySecretKey";  // 可以在配置文件中读取
    private static final byte[] SECRET_KEY_BYTES = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
    private static final long EXPIRATION_TIME = 86400000;  // 24小时过期

    /**
     * 获取token中的参数
     *
     * @param token
     * @param key
     * @return
     */
    public static Claims parseToken(String token, String key) {
        if ("".equals(token)) {
            return null;
        }

        try {
            byte[] signingKey = key.getBytes(StandardCharsets.UTF_8);
            return Jwts.parser()
                    .setSigningKey(signingKey)
                    .parseClaimsJws(token).getBody();
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 从token中获取用户名
     *
     * @param token
     * @return
     */
    public static String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY_BYTES)
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    /**
     * 从token中获取用户ID
     *
     * @param token
     * @return
     */
    public static Integer getUserIdFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY_BYTES)
                .parseClaimsJws(token)
                .getBody();
        return (Integer) claims.get("userId"); // 从claims中获取userId
    }

    /**
     * 从token中获取iaAdmin
     *
     * @param token
     * @return
     */
    public static Integer getIsAdminFromToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY_BYTES)
                .parseClaimsJws(token)
                .getBody();
        return (Integer) claims.get("isAdmin"); // 从claims中获取isAdmin
    }

    /**
     * 生成token
     *
     * @param userId
     * @param username
     * @return
     */
    public static String generateToken(Integer userId, String username,Integer isAdmin,Integer role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", username);
        claims.put("userId", userId);
        claims.put("isAdmin", isAdmin);
        claims.put("role", role);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY_BYTES)
                .compact();
    }

    /**
     * 校验token是否合法
     *
     * @param token
     * @return
     */
    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY_BYTES).parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
            System.out.println("Token过期");
        } catch (Exception e) {
            System.out.println("Token无效");
        }
        return false;
    }

    public static void main(String[] args) {
        // 生成 token
        String token =  "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkYW94aWFuZyIsImlzQWRtaW4iOjEsImV4cCI6MTc0MjM0NzA5OSwidXNlcklkIjoxLCJpYXQiOjE3NDIyNjA2OTksInVzZXJuYW1lIjoiZGFveGlhbmcifQ.Q_NLNP5X5CDv2aR2EjgFRHi5g92q0WvIcbSru5i651_uQh2SQcBVwklSRhrpqa8TmX2lKOlr43mjw2aLUwSsyQ";//JWTUtils.generateToken(1, "zhangsan",1);
        System.out.println("Generated Token: " + token);

        // 解析 token 获取 username
        String username = JWTUtils.getUsernameFromToken(token);
        System.out.println("Username from Token: " + username);

        // 解析 token 获取 userId
        Integer userId = JWTUtils.getUserIdFromToken(token);
        System.out.println("User ID from Token: " + userId);

        Integer isAdminFromToken = JWTUtils.getIsAdminFromToken(token);
        System.out.println("isAdmin: "+isAdminFromToken);

        // 校验 token
        boolean isValid = JWTUtils.validateToken(token);
        System.out.println("Is Token valid? " + isValid);
    }
}
